package com.baidu.util.time.nlp.festival;

import com.baidu.util.time.nlp.TimeAnalyze;
import com.baidu.util.time.nlp.festival.strategy.FestivalDayStrategy;
import org.apache.commons.io.IOUtils;
import org.joda.time.DateTime;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FestivalDayAnalyse {
    private List<FestivalDayInfo> festivalDayInfoList;
    private static FestivalDayAnalyse festivalDayAnalyse = new FestivalDayAnalyse();

    public static FestivalDayAnalyse getInstance() {
        return festivalDayAnalyse;
    }

    private FestivalDayAnalyse() {
        List<String> textList = null;
        try {
            textList = IOUtils.readLines(TimeAnalyze.class.getResourceAsStream("/festivalday.txt"), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        }
        festivalDayInfoList = getFestivalDayInfoList(textList);
    }

    /**
     * 提取节假日
     *
     * @param text
     * @param baseTime
     * @return
     */
    public DateTime execute(String text, DateTime baseTime) {
        DateTime dateTime = null;
        if (festivalDayInfoList.isEmpty()) {
            return null;
        }
        for (FestivalDayInfo info : festivalDayInfoList) {
            FestivalDayStrategy strategy = FestivalDayFactory.getFestivalDayStrategy(info.getType());
            dateTime = strategy.getDateTime(text, baseTime, info);
            if (dateTime != null) {
                return dateTime;
            }
        }
        return null;
    }

    public DateTime execute(String text) {
        return execute(text, DateTime.now());
    }

    private List<FestivalDayInfo> getFestivalDayInfoList(List<String> textList) {
        List<FestivalDayInfo> resultList = new ArrayList<>();
        if (textList.isEmpty()) {
            return resultList;
        }
        for (String text : textList) {
            resultList.add(new FestivalDayInfo(text));
        }
        return resultList;
    }
}
